/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.common.converter;

import han.bashe.common.exception.BasheErrorCode;
import han.bashe.common.exception.BasheException;
import han.bashe.common.message.MessageHeaderConstants;
import han.bashe.common.message.NormalizedMessage;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.xmlbeans.XmlObject;

/**
 * @Author Kent
 */
public class HttpConverter {

	public static NormalizedMessage toNormalized(HttpServletRequest request)
			throws Exception {
		String xml = ServletReqResHeler.getRequestString(request);
		Enumeration<String> names = request.getHeaderNames();
		NormalizedMessage msg = new NormalizedMessage();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			if (name.startsWith(MessageHeaderConstants.HEAD_PREFIX)
					|| name
							.startsWith(MessageHeaderConstants.HEAD_CUSTOM_PREFIX)) {
				msg.setHead(name, request.getHeader(name));
			}
		}
		try{
			XmlObject o = XmlObject.Factory.parse(xml);
		}catch(Exception e){
			throw new BasheException(BasheErrorCode.PARSE_CLIENT_XML_ERROR,"HTTP Body is not a valid xml",e);
		}
		msg.setBody(xml);
		return msg;
	}

	public static void toHttpResponse(NormalizedMessage msg,
			HttpServletResponse response) {
		for (String key : msg.getHeads().keySet()) {
			response.addHeader(key, msg.getHead(key));
		}
		ServletReqResHeler.setResponseString(response, (String) msg.getBody());
	}

	public static String toHttpRequest(NormalizedMessage msg, PostMethod post) {
		for (String key : msg.getHeads().keySet()) {
			post.addRequestHeader(key, msg.getHead(key));
		}
		return msg.getBody();
	}

	public static NormalizedMessage toNormalized(PostMethod post, boolean req)
			throws Exception {

		NormalizedMessage ret = new NormalizedMessage();
		if (req) {
			for (Header h : post.getRequestHeaders()) {
				if (h.getName().startsWith(
						MessageHeaderConstants.HEAD_CUSTOM_PREFIX)) {
					ret.setHead(h.getName(), h.getValue());
				}
			}
		}// else means this is response 
		else {
			//System.out.println(post.getResponseHeaders());
			for (Header h : post.getResponseHeaders()) {
				//System.out.println(h.getName());
				if (h.getName().startsWith(
						MessageHeaderConstants.HEAD_CUSTOM_PREFIX)
					|| h.getName().startsWith(
							MessageHeaderConstants.HEAD_PREFIX)) {
					ret.setHead(h.getName(), h.getValue());
				}
			}
		}
		ret.setBody(post.getResponseBodyAsString());
		return ret;
	}
}
